package com.mrd.gtimp.base.action;

import com.mrd.constant.BaseTypeConstant;
import com.mrd.constant.SpecialConstant;
import com.mrd.constant.StateConstats;
import com.mrd.exception.QueryException;
import com.mrd.framework.ui.Jqgrid;
import com.mrd.framework.ui.filter.Filter;
import com.mrd.framework.ui.filter.SearchRule;
import com.mrd.framework.ui.filter.SearchRuleOption;
import com.mrd.framework.utils.HttpUtils;
import com.mrd.gtimp.base.entity.Company;
import com.mrd.gtimp.base.entity.SystemValue;
import com.mrd.gtimp.base.entity.User;
import com.mrd.gtimp.base.service.CompanyBiz;
import com.mrd.gtimp.base.service.SystemValueBiz;
import com.mrd.gtimp.base.service.UserBiz;
import com.mrd.gtimp.business.entity.Commodity;
import com.mrd.gtimp.business.entity.Declaration;
import com.mrd.gtimp.business.service.CommodityBiz;
import com.mrd.gtimp.business.service.DeclarationBiz;
import com.mrd.gtimp.sup.entity.SupCustomerRole;
import com.mrd.gtimp.sup.service.SupCustomerBiz;
import com.mrd.gtimp.sup.service.SupCustomerRoleBiz;
import com.mrd.util.LoginUtil;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

/**
 * 下拉框对象 返回前台的结果变量，格式为[[显示值，真实值],[显示值1，真实值1],...]
 *
 * @author qiul
 */

@Controller
@RequestMapping("/base")
public class DropdownAction {
    private static final long serialVersionUID = 1L;
    private static final Logger logger = LoggerFactory.getLogger(DropdownAction.class);
    private static final int PAGE_SIZE = 5;
    @Resource
    private CompanyBiz companyBiz;
    @Resource
    private SupCustomerRoleBiz supCustomerRoleBiz;
    @Resource
    private SystemValueBiz systemValueBiz;
    @Resource
    private UserBiz userBiz;
    @Resource
    private SupCustomerBiz supCustomerBiz;

    /**
     * 基础数据表的所有数据,Map<基础数据类型的identifier值，对应的集合>
     */
    private static final Map<String, List<SystemValue>> baseValues = new HashMap<>();

    /**
     * 启用状态
     */
    @RequestMapping("/dropdown-useState")
    @ResponseBody
    public String[][] useState() {
        return StateConstats.USE_STATE;
    }

    /**
     * 隐藏状态
     */
    @RequestMapping("/dropdown-hiddenState")
    @ResponseBody
    public String[][] hiddenState() {
        return StateConstats.HIDDEN_STATE;
    }

    /**
     * 业务类型
     */
    @RequestMapping("/dropdown-businessType")
    @ResponseBody
    public String[][] businessType() {
        return getBasicDataWithIdentifier(BaseTypeConstant.BUSINESS_TYPE);
    }

    /**
     * 订舱业务数据--业务类型
     */
    @RequestMapping("/dropdown-bookingBusinessType")
    @ResponseBody
    public String[][] bookingBusinessType() {
        return getBasicDataWithIdentifier(BaseTypeConstant.BOOKING_BIZ_TYPE);
    }

    /**
     * 公司类型
     */
    @RequestMapping("/dropdown-companyType")
    @ResponseBody
    public String[][] companyType() {
        return getBasicDataWithIdentifier(BaseTypeConstant.COMPANY_TYPE);
    }

    /**
     * 订舱业务状态
     */
    @RequestMapping("/dropdown-bookingState")
    @ResponseBody
    public String[][] bookingState(User user) {
        try {
            Filter filters = new Filter();
            boolean iamSup = false;
            if (user.getCompany().getType().equals(BaseTypeConstant.COMPANY_TYPE_SUP)) {
                filters.addRule(new SearchRule("identifier", SearchRuleOption.ne, BaseTypeConstant.BOOKINGSTATE_00));
                iamSup = true;
            }
            filters.addRule(new SearchRule("parentId", SearchRuleOption.eq, BaseTypeConstant.BOOKING_STATE_TYPE_PID));
            Pageable page = new PageRequest(1, PAGE_SIZE, new Sort("identifier"));
            Jqgrid jqgrid = new Jqgrid(filters, page);
            Page<SystemValue> sysvals = systemValueBiz.findByJqgrid(jqgrid);
            String[][] results = new String[sysvals.getSize()][2];
            for (int i = 0; i < results.length; i++) {
                if (iamSup
                        && SpecialConstant.VALIDATE_STATE_CUSTOMER_VIEW.equals(sysvals.getContent().get(i)
                        .getChn())) {
                    results[i][0] = SpecialConstant.VALIDATE_STATE_SUP_VIEW;
                } else {
                    results[i][0] = sysvals.getContent().get(i).getChn();
                }
                results[i][1] = sysvals.getContent().get(i).getIdentifier();
            }
            return results;
        } catch (Exception e) {
            logger.error("数据转换成下拉框数据时发生错误!", e);
            return null;
        }
    }

    /**
     * 拖车业务状态
     */
    @RequestMapping("/dropdown-trailState")
    @ResponseBody
    public String[][] trailState(User user) {
        try {
            Filter filters = new Filter();
            boolean iamSup = false;
            if (user.getCompany().getType().equals(BaseTypeConstant.COMPANY_TYPE_SUP)) {
                filters.addRule(new SearchRule("identifier", SearchRuleOption.ne, BaseTypeConstant.TRAILSTATE_00));
                iamSup = true;
            }
            filters.addRule(new SearchRule("parentId", SearchRuleOption.eq, BaseTypeConstant.TRAIL_STATE_TYPE_PID));
//            List<SystemValue> sysvals = systemValueBiz.findByJqgrid(1, 7, filters, new Sort.Order(""));
            Pageable page = new PageRequest(1, 7, new Sort("identifier")); // 将拖车的下拉选项的个数设为7个
            Jqgrid jqgrid = new Jqgrid(filters, page);
            Page<SystemValue> sysvals = systemValueBiz.findByJqgrid(jqgrid);
            String[][] results = new String[sysvals.getSize()][2];
            for (int i = 0; i < results.length; i++) {
                if (iamSup
                        && SpecialConstant.VALIDATE_STATE_CUSTOMER_VIEW.equals(sysvals.getContent().get(i)
                        .getChn())) {
                    results[i][0] = SpecialConstant.VALIDATE_STATE_SUP_VIEW;
                } else {
                    results[i][0] = sysvals.getContent().get(i).getChn();
                }
                results[i][1] = sysvals.getContent().get(i).getIdentifier();
            }
            return results;
        } catch (Exception e) {
            logger.error("数据转换成下拉框数据时发生错误!", e);
            return null;
        }
    }

    /**
     * 报关业务状态
     */
    @RequestMapping("/dropdown-declarationState")
    @ResponseBody
    public Page<SystemValue> declarationState(User user) {
        try {
            Filter filters = new Filter();
            boolean iamSup = false;
            if (user.getCompany().getType().equals(BaseTypeConstant.COMPANY_TYPE_SUP)) {
                filters.addRule(new SearchRule("identifier", SearchRuleOption.ne, BaseTypeConstant.DECLARATIONSTATE_00));
                iamSup = true;
            }
            filters.addRule(new SearchRule("parentId", SearchRuleOption.eq, BaseTypeConstant.DECLARATION_TYPE_PID));
            Pageable page = new PageRequest(1, PAGE_SIZE, new Sort("identifier"));
            Jqgrid jqgrid = new Jqgrid(filters, page);
            Page<SystemValue> sysvals = systemValueBiz.findByJqgrid(jqgrid);
            String[][] results = new String[sysvals.getSize()][2];
            for (int i = 0; i < results.length; i++) {
                if (iamSup
                        && SpecialConstant.VALIDATE_STATE_CUSTOMER_VIEW.equals(sysvals.getContent().get(i)
                        .getChn())) {
                    results[i][0] = SpecialConstant.VALIDATE_STATE_SUP_VIEW;
                } else {
                    results[i][0] = sysvals.getContent().get(i).getChn();
                }
                results[i][1] = sysvals.getContent().get(i).getIdentifier();
            }
            return sysvals;
        } catch (Exception e) {
            logger.error("数据转换成下拉框数据时发生错误!", e);
            return null;
        }
    }

    /**
     * 业务流程状态
     */
    @RequestMapping("/dropdown-processState")
    @ResponseBody
    public String[][] processState() {
        try {
            Filter filters = new Filter();
            filters.addRule(new SearchRule("parentId", SearchRuleOption.eq, BaseTypeConstant.PROCESS_STATE));
//            List<SystemValue> sysvals = systemValueBiz
//                    .findByJqgrid(1, PAGE_SIZE, filters, new Sort.Order("identifier"));
            Pageable page = new PageRequest(1, PAGE_SIZE, new Sort("identifier"));
            Jqgrid jqgrid = new Jqgrid(filters, page);
            Page<SystemValue> sysvals = systemValueBiz.findByJqgrid(jqgrid);
            String[][] results = new String[sysvals.getSize()][2];
            for (SystemValue systemValue : sysvals) {
                results[sysvals.getContent().indexOf(systemValue)][0] = systemValue.getChn();
                results[sysvals.getContent().indexOf(systemValue)][1] = systemValue.getIdentifier();
            }
            return results;
        } catch (Exception e) {
            logger.error("数据转换成下拉框数据时发生错误!", e);
            return null;
        }
    }

    /**
     * 退税单状态
     */
    @RequestMapping("/dropdown-taxState")
    @ResponseBody
    public String[][] taxState() {
        try {
            /*
             * if(k == null || !"".equals(k.trim())) {
			 * filters.addRule(new SearchRule("name", SearchRuleOption.cn, k));
			 * }
			 */
            Filter filters = new Filter();
            filters.addRule(new SearchRule("parentId", SearchRuleOption.eq, BaseTypeConstant.TAX_STATE_TYPE_ID));
            Pageable page = new PageRequest(1, PAGE_SIZE, new Sort("identifier"));
            Jqgrid jqgrid = new Jqgrid(filters, page);
            Page<SystemValue> sysvals = systemValueBiz.findByJqgrid(jqgrid);
            String[][] results = new String[sysvals.getSize()][2];
            for (int i = 0; i < results.length; i++) {
                results[i][0] = sysvals.getContent().get(i).getChn();
                results[i][1] = sysvals.getContent().get(i).getIdentifier();
            }
            return results;
        } catch (Exception e) {
            logger.error("数据转换成下拉框数据时发生错误!", e);
            return null;
        }
    }

    /**
     * 供应商
     */
    @RequestMapping("/dropdown-supCop")
    @ResponseBody
    public String[][] supCop(@RequestParam(required = false) String k) {
        try {
            Jqgrid jqgrid = new Jqgrid();
            if (StringUtils.isNotEmpty(k)) {
                jqgrid.addRule(new SearchRule("name", SearchRuleOption.cn, k.trim()));
            }
            jqgrid.addRule(new SearchRule("type", SearchRuleOption.eq, "CC"));
            Page<Company> companies = companyBiz.findByJqgrid(jqgrid);
            String[][] results = new String[companies.getContent().size()][2];
            for (int i = 0; i < results.length; i++) {
                results[i][0] = companies.getContent().get(i).getName();
                results[i][1] = companies.getContent().get(i).getId();
            }
            return results;
        } catch (Exception e) {
            logger.error("数据转换成下拉框数据时发生错误!", e);
            return null;
        }
    }

    /**
     * 下拉条--选择供应商(用户列表查询)
     */
    @RequestMapping("/dropdown-findCompanysByNameType")
    @ResponseBody
    public String[][] findCompanysByNameType() {
        try {
            Filter filters = new Filter();
            String com_type = HttpUtils.getParam("com_type");
            String sup_type = HttpUtils.getParam("sup_type");
            String com_name = HttpUtils.getParam("com_name");
            SearchRule sr = new SearchRule("type", SearchRuleOption.eq, com_type);
            filters.addRule(sr);
            if (null != com_name && !"".equals(com_name)) {
                SearchRule sr2 = new SearchRule("name", SearchRuleOption.cn, com_name);
                filters.addRule(sr2);
            }
            if (null != sup_type && !"".equals(sup_type)) {
                SearchRule sr3 = new SearchRule("supTypes.identifier", SearchRuleOption.eq, sup_type);
                filters.addRule(sr3);
            }
//            companys = companyBiz.findEntityByFilter(0, 10, filters, null);
            Pageable page = new PageRequest(1, 10, new Sort(""));
            Jqgrid jqgrid = new Jqgrid(filters, page);
            Page<Company> companys = companyBiz.findByJqgrid(jqgrid);
            String[][] results = new String[companys.getSize()][2];
            for (int i = 0; i < results.length; i++) {
                results[i][0] = companys.getContent().get(i).getName();
                results[i][1] = companys.getContent().get(i).getId();
            }
            return results;
        } catch (Exception e) {
            logger.error("数据转换成下拉框数据时发生错误!", e);
            return null;
        }
    }

    /**
     * 自己的供应商
     */
    @RequestMapping("/dropdown-selfSupCop")
    @ResponseBody
    public String[][] selfSupCop(@RequestParam(required = false) String k) {
        try {
            Filter filters = new Filter();
            String supIds = supCustomerBiz.getSelfSupCompanyStr(LoginUtil.getLoginUser());
            if (StringUtils.isNotEmpty(supIds)) {
                if (k == null || !"".equals(k.trim())) {
                    filters.addRule(new SearchRule("name", SearchRuleOption.cn, k));
                }
                filters.addRule(new SearchRule("type", SearchRuleOption.eq, BaseTypeConstant.COMPANY_TYPE_SUP));
                filters.addRule(new SearchRule("id", SearchRuleOption.in, supIds));
                Pageable page = new PageRequest(1, PAGE_SIZE, new Sort("name"));
                Jqgrid jqgrid = new Jqgrid(filters, page);
                Page<Company> companies = companyBiz.findByJqgrid(jqgrid);
                String[][] results = new String[companies.getSize()][2];
                for (int i = 0; i < results.length; i++) {
                    results[i][0] = companies.getContent().get(i).getName();
                    results[i][1] = companies.getContent().get(i).getId();
                }
                return results;
            } else {
                return null;
            }
        } catch (Exception e) {
            logger.error("数据转换成下拉框数据时发生错误!", e);
            return null;
        }
    }

    /**
     * 根据com_type（公司类型）和sup_type（业务类型）查找公司
     */
    @RequestMapping("/dropdown-supComByNameType")
    @ResponseBody
    public String[][] supComByNameType(@RequestParam(required = false) String k) {
        try {
            Filter filters = new Filter();
            if (k == null || !"".equals(k.trim())) {
                filters.addRule(new SearchRule("name", SearchRuleOption.cn, k));
            }
            String com_type = HttpUtils.getParam("com_type");
            String sup_type = HttpUtils.getParam("sup_type");
            String decidePara = HttpUtils.getParam("decidePara");
            if (com_type.equals(BaseTypeConstant.COMPANY_TYPE_SHIP)) {
                return shipCom(k);
            }
            SearchRule sr = new SearchRule("type", SearchRuleOption.eq, com_type);
            filters.addRule(sr);
            if (null != sup_type && !"".equals(sup_type)) {
                SearchRule sr3 = new SearchRule("supTypes.identifier", SearchRuleOption.eq, sup_type);
                filters.addRule(sr3);
            }
//            List<Company> companies = companyBiz.findByJqgrid(1, PAGE_SIZE, filters, new Sort.Order("name"));
            Pageable page = new PageRequest(1, PAGE_SIZE, new Sort("name"));
            Jqgrid jqgrid = new Jqgrid(filters, page);
            Page<Company> companies = companyBiz.findByJqgrid(jqgrid);
            String[][] results = new String[companies.getSize()][2];
            int j = 0;
            boolean isSupBooking = false;
            for (int i = 0; i < results.length; i++) {
                // if("supBooking".equals(decidePara) && "佛山新港".equals(companies.get(i).getName()))
                // {
                if ("supBooking".equals(decidePara) && "宏达货代".equals(companies.getContent().get(i).getName())) {
                    isSupBooking = true;
                    continue;
                }
                results[j][0] = companies.getContent().get(i).getName();
                results[j][1] = companies.getContent().get(i).getId();
                j++;
            }
            if (isSupBooking) {
                String[][] temp = new String[1][2];
                temp[0][0] = results[0][0];
                temp[0][1] = results[0][1];
                results = new String[1][2];
                results[0][0] = temp[0][0];
                results[0][1] = temp[0][1];
            }
            return results;
        } catch (Exception e) {
            logger.error("数据转换成下拉框数据时发生错误!", e);
            return null;
        }
    }

    /**
     * 大船公司
     */
    @RequestMapping("/dropdown-shipCom")
    @ResponseBody
    public String[][] shipCom(@RequestParam(required = false) String k) {
        try {
            /*
             * filters.addRule(new SearchRule("name", SearchRuleOption.cn, k));
			 * filters.addRule(new SearchRule("type", SearchRuleOption.eq, "SC"));
			 * Order order = new Order();
			 * order.add("name");
			 */
            k = k.trim();
            String hql = "from Company c where (lower(c.name) like '%" + k
                    + "%' or lower(c.SHORT_NAME) like '%" + k + "%') and c.type = 'SC' ";
            List<Company> companies = companyBiz.findEntityByHql(hql, 1, PAGE_SIZE, null);
            String[][] results = new String[companies.size()][2];
            for (int i = 0; i < results.length; i++) {
                results[i][0] = companies.get(i).getName() + " " + companies.get(i).getSHORT_NAME();
                results[i][1] = companies.get(i).getId();
            }
            return results;
        } catch (Exception e) {
            logger.error("数据转换成下拉框数据时发生错误!", e);
            return null;
        }
    }

    /**
     * 公司
     */
    @RequestMapping("/dropdown-company")
    @ResponseBody
    public String[][] company(@RequestParam(required = false) String k) {
        try {
            if (StringUtils.isNotBlank(k)) {
                k = k.trim();
                Jqgrid jqgrid = new Jqgrid();
                jqgrid.addRule(new SearchRule("name", SearchRuleOption.cn, k));
                jqgrid.addOrder(Sort.Direction.DESC, "name");
                Page<Company> companies = companyBiz.findByJqgrid(jqgrid);
                String[][] results = new String[companies.getContent().size()][2];
                for (int i = 0; i < results.length; i++) {
                    results[i][0] = companies.getContent().get(i).getName();
                    results[i][1] = companies.getContent().get(i).getId();
                }
                return results;
            }
        } catch (Exception e) {
            logger.error("数据转换成下拉框数据时发生错误!", e);
            return null;
        }
        return null;
    }

    /**
     * 柜型
     */
    @RequestMapping("/dropdown-ctType")
    @ResponseBody
    public String[][] ctType() {
        return setResultByBaseTypeWithIdentifier(BaseTypeConstant.CT_TYPE);
    }

    /**
     * 柜尺寸
     */
    @RequestMapping("/dropdown-ctSize")
    @ResponseBody
    public String[][] ctSize() {
        return setResultByBaseTypeWithIdentifier(BaseTypeConstant.CT_SIZE);
    }

    @RequestMapping("/dropdown-supCustomerRole")
    @ResponseBody
    public String[][] supCustomerRole(@RequestParam(required = false) String k) {
        try {
            Filter filters = new Filter();
            if (null != k && !"".equals(k.trim())) {
                filters.addRule(new SearchRule("NAME", SearchRuleOption.cn, k.trim()));
            }
            filters.addRule(new SearchRule("COM_ID", SearchRuleOption.eq, LoginUtil.getLoginUser().getCompany().getId()));
//            List<SupCustomerRole> customerRoles = supCustomerRoleBiz
//                    .findByJqgrid(1, PAGE_SIZE, filters, new Sort.Order("NAME"));
            Pageable page = new PageRequest(1, PAGE_SIZE, new Sort("NAME"));
            Jqgrid jqgrid = new Jqgrid(filters, page);
            Page<SupCustomerRole> customerRoles = supCustomerRoleBiz.findByJqgrid(jqgrid);
            String[][] results = new String[customerRoles.getSize()][2];
            for (int i = 0; i < results.length; i++) {
                results[i][0] = customerRoles.getContent().get(i).getNAME();
                results[i][1] = customerRoles.getContent().get(i).getID();
            }
            return results;
        } catch (Exception e) {
            logger.error("数据转换成下拉框数据时发生错误!", e);
            return null;
        }
    }

    /**
     * 权限类型
     */
    @RequestMapping("/dropdown-pmsType")
    @ResponseBody
    public String[][] pmsType() {
        return getBasicDataWithIdentifier(BaseTypeConstant.PERMISSIONS_TYPE);
    }

    /**
     * 获取码头
     */
    @RequestMapping("/dropdown-port")
    @ResponseBody
    public String[][] port(@RequestParam(required = false) String k) {
        return getBasicDataWithIdentifier(BaseTypeConstant.PORT_TYPE);
    }

    @RequestMapping("/dropdown-cusCompany")
    @ResponseBody
    public String[][] cusCompany(@RequestParam(required = false) String k) {
        try {
            k = k.trim();
            String hql = "from Company c where (lower(c.name) like '%" + k
                    + "%' or lower(c.SHORT_NAME) like '%" + k + "%') and c.type = 'SC' ";
            List<Company> companies = companyBiz.findEntityByHql(hql, 1, PAGE_SIZE, null);
            String[][] results = new String[companies.size()][2];
            for (int i = 0; i < results.length; i++) {
                results[i][0] = companies.get(i).getName() + " " + companies.get(i).getSHORT_NAME();
                results[i][1] = companies.get(i).getId();
            }
            return results;
        } catch (Exception e) {
            logger.error("数据转换成下拉框数据时发生错误!", e);
            return null;
        }
    }

    /**
     * 供应商业务员帐号列表
     */
    @RequestMapping("/dropdown-supLinkedUser")
    @ResponseBody
    public String[][] supLinkedUser(@RequestParam(required = false) String k, Filter filters) {
        try {
            if (null != k && !"".equals(k.trim())) {
                filters.addRule(new SearchRule("name", SearchRuleOption.cn, k.trim()));
            }
            filters.addRule(new SearchRule("depts.company.id", SearchRuleOption.eq, LoginUtil.getLoginUser()
                    .getCompany().getId()));
//            List<User> userList = userBiz.findByJqgrid(1, PAGE_SIZE, filters, new Sort.Order("name"));
            Pageable page = new PageRequest(1, PAGE_SIZE, new Sort("name"));
            Jqgrid jqgrid = new Jqgrid(filters, page);
            Page<User> userList = userBiz.findByJqgrid(jqgrid);
            String[][] results = new String[userList.getSize()][2];
            for (int i = 0; i < results.length; i++) {
                results[i][0] = userList.getContent().get(i).getName();
                results[i][1] = userList.getContent().get(i).getId();
            }
            return results;
        } catch (Exception e) {
            logger.error("数据转换成下拉框数据时发生错误!", e);
            return null;
        }
    }

    /**
     * 报关成交单位
     */
    @RequestMapping("/dropdown-unit")
    @ResponseBody
    public String[][] unit() {
        try {
            return systemValueBiz.findUnitsOfMeasurement();
        } catch (Exception e) {
            logger.error("数据转换成下拉框数据时发生错误!", e);
            return null;
        }
    }

    /**
     * 获取基础数据的标示，用于下拉框中，显示值和真实值均为表示码
     */
    private String[][] setResultByBaseTypeWithIdentifier(String baseType) {
        List<SystemValue> systemValues = baseValues.get(baseType);
        if (systemValues != null && systemValues.size() != 0) {
            String[][] results = new String[systemValues.size()][2];
            for (int i = 0; i < results.length; i++) {
                results[i][0] = systemValues.get(i).getIdentifier();
                results[i][1] = systemValues.get(i).getIdentifier();
            }
            return results;
        } else {
            return NON_RESULTS;
        }
    }

    /**
     * 未找到数据时的返回
     */
    private static final String[][] NON_RESULTS = {{"未找到数据", "\"\""}};

    /**
     * 根据基础数据的父类型，将数据转换成数据，数据第一个值为中文，第二个值为编号，第三个值为英文
     *
     * @param type 自定义标识
     * @return 数组
     */
    private String[][] getBasicDataWithIdentifier(String type) {
        try {
            if (baseValues.size() == 0) {
                synchronized (baseValues) {
                    if (baseValues.size() == 0) {// 第二次判断是为了防止，在同步过程中其他线程进行到，该处时造成baseValues的脏读
                        try {
                            initBaseValue();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
            List<SystemValue> systemValues = baseValues.get(type);
            if (CollectionUtils.isEmpty(systemValues)) {
                return NON_RESULTS;
            }
            String[][] results = new String[systemValues.size()][3];
            for (int i = 0; i < results.length; i++) {
                results[i][0] = systemValues.get(i).getChn();// 此处是查询中文下拉
                results[i][1] = systemValues.get(i).getIdentifier();
                results[i][2] = systemValues.get(i).getEn();// 此处是查询英文下拉
            }
            return results;
        } catch (Exception e) {
            logger.error("转换下拉框数据时发生错误!", e);
            return NON_RESULTS;
        }
    }

    /**
     * 初始化基础数据到缓存
     */
    private void initBaseValue() {
        try {
            baseValues.clear();
            List<SystemValue> sv = systemValueBiz.findAllEntity();
            Map<String, SystemValue> topLev = new HashMap<>();
            sv.stream().filter(systemValue -> StringUtils.isEmpty(systemValue.getParentId())).forEach(systemValue -> topLev.put(systemValue.getId(), systemValue));
            sv.stream().filter(systemValue -> StringUtils.isNotEmpty(systemValue.getParentId()) && topLev.get(systemValue.getParentId()) != null).forEach(systemValue -> {
                String parent_idf = topLev.get(systemValue.getParentId()).getIdentifier();
                List<SystemValue> list = baseValues.get(parent_idf);
                if (list == null) {
                    list = new ArrayList<>();
                    list.add(systemValue);
                    baseValues.put(parent_idf, list);
                } else {
                    list.add(systemValue);
                }
            });
        } catch (Exception e) {
            logger.error("初始化下拉框数据时发生错误!", e);
        }
    }


    //====================gtimp 3.0======================

    @Resource
    private DeclarationBiz declarationBiz;

    @Resource
    private CommodityBiz commodityBiz;

    @RequestMapping("/getCompanyByComType")
    @ResponseBody
    public String[][] getCompanyByComType(String k, String comType) {
        Jqgrid jqgrid = new Jqgrid();
        jqgrid.setSize(PAGE_SIZE);
        try {
            if (StringUtils.isNotEmpty(comType)) {
                jqgrid.addRule(new SearchRule("type", SearchRuleOption.eq, comType));
            }
            if (StringUtils.isNotEmpty(k)) {
                jqgrid.addRule(new SearchRule("name", SearchRuleOption.cn, k.trim()));
            }
            Page<Company> companyPage = companyBiz.findByJqgrid(jqgrid);
            List<Company> companyList = companyPage.getContent();
            if (companyList != null && companyList.size() > 0) {
                String[][] result = new String[companyList.size()][3];
                for (int i = 0; i < companyList.size(); i++) {
                    Company company = companyList.get(i);
                    result[i][0] = company.getName();
                    result[i][1] = company.getId();
                    result[i][2] = company.getCom_customs_code();
                }
                return result;
            }
        } catch (QueryException e) {
            e.printStackTrace();
        }
        return null;
    }

    @RequestMapping("/getContainerNoByDeclarationId")
    @ResponseBody
    public String[] getContainerNoByDeclarationId(String declarationId, Jqgrid jqgrid) {
        try {
            jqgrid.addRule(new SearchRule("id", SearchRuleOption.eq, declarationId));
            Page<Declaration> declarationPage = declarationBiz.findByJqgrid(jqgrid);
            List<Declaration> declarationList = declarationPage.getContent();
            if (declarationList != null && declarationList.size() > 0) {
                String container_no_str = null;
                for (Declaration declaration : declarationList) {
                    container_no_str = declaration.getContainer_no();
                }
                if (StringUtils.isNotEmpty(container_no_str)) {
                    String[] container_no_array = container_no_str.split(",");
                    return container_no_array;
                }
            }
        } catch (QueryException e) {
            e.printStackTrace();
        }
        return null;
    }

    @RequestMapping("/getCommodityByDeclarationId")
    @ResponseBody
    public String[][] getCommodityByDeclarationId(String declarationId, Jqgrid jqgrid) {
        try {
            jqgrid.addRule(new SearchRule("declaration.id", SearchRuleOption.eq, declarationId));
            Page<Commodity> commodityPage = commodityBiz.findByJqgrid(jqgrid);
            List<Commodity> commodityList = commodityPage.getContent();
            if (commodityList != null && commodityList.size() > 0) {
                String[][] result = new String[commodityList.size()][2];
                for (int i = 0; i < commodityList.size(); i++) {
                    Commodity commodity = commodityList.get(i);
                    result[i][0] = commodity.getId();
                    result[i][1] = commodity.getName() + "-" + commodity.getGoods_mode();
                }
                return result;
            }
        } catch (QueryException e) {
            e.printStackTrace();
        }
        return null;
    }
}
